package com.cskaoyan.service.impl;

import com.cskaoyan.mapper.AdminMapper;
import com.cskaoyan.mapper.PermissionMapper;
import com.cskaoyan.mapper.ResourceTableMapper;
import com.cskaoyan.mapper.RoleMapper;
import com.cskaoyan.model.*;
import com.cskaoyan.model.bo.RoleBO;
import com.cskaoyan.model.bo.BaseParamBO;
import com.cskaoyan.model.bo.RolePermissionBO;
import com.cskaoyan.model.vo.*;
import com.cskaoyan.service.RoleService;
import com.cskaoyan.util.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @program: mall38
 * @description: 角色管理
 * @author: Lexis
 * @create: 2022-05-05 19:01
 **/
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    ResourceTableMapper resourceTableMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Autowired
    AdminMapper adminMapper;

    @Override
    /**
     * @author: lixiaosheng
     * @description: 获取所有的角色
     * @date: 2022/5/5 19:36
     */
    public DataVO<GetRoleVO> query(BaseParamBO param) {
        Integer page = param.getPage();//页码
        Integer limit = param.getLimit();//数据量
        PageHelper.startPage(page, limit);
        List<GetRoleVO> list = roleMapper.select();

        PageInfo<GetRoleVO> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return DataVO.data(total, pages, limit, page, list);
    }

    @Transactional
    @Override
    /**
     * @author: lixiaosheng
     * @description: 插入一个角色
     * @date: 2022/5/5 23:32
     */
    public Role create(RoleBO roleBO) {
        Role role = new Role();
        role.setAddTime(new Date());
        role.setUpdateTime(new Date());
        role.setDesc(roleBO.getDesc());
        role.setName(roleBO.getName());
        roleMapper.insertSelective(role);
        return role;
    }

    @Override
    public DataVO<Role> queryRole(BaseParamBO param, String name) {
        Integer page = param.getPage();//页码
        Integer limit = param.getLimit();//数据量
        //分页插件 PageHelper，辅助我们做分页以及分页信息的获得
        PageHelper.startPage(page, limit);
        RoleExample roleExample = new RoleExample();

        roleExample.setOrderByClause(param.getSort() + " " + param.getOrder());

        RoleExample.Criteria criteria = roleExample.createCriteria();
        if (!StringUtil.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);
        List<Role> list = roleMapper.selectByExample(roleExample);
        PageInfo<Role> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return DataVO.data(total, pages, limit, page, list);
    }

    @Transactional
    @Override
    /**
     * @author: lixiaosheng
     * @description: 更新角色信息
     * @date: 2022/5/6 14:26
     */
    public void update(Role role) {
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andIdEqualTo(role.getId());
        criteria.andDeletedEqualTo(false);
        role.setId(null);
        roleMapper.updateByExampleSelective(role, roleExample);
    }

    @Transactional
    @Override
    /**
     * @author: lixiaosheng
     * @description: 根据主键逻辑删除一条角色
     * @date: 2022/5/6 14:46
     */
    public void delete(Role role) {
        Role role1 = new Role();
        role1.setId(role.getId());
        role1.setDeleted(true);
        roleMapper.updateByPrimaryKeySelective(role1);
        // 更新管理员信息
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        List<Admin> admins = adminMapper.selectAdminByRoleId(role.getId().toString());
        for (Admin admin : admins) {
            Integer[] roleIds1 = admin.getRoleIds();
            if (roleIds1 != null) {
                List<Integer> roleIds = new ArrayList<>();
                roleIds.addAll(Arrays.asList(admin.getRoleIds()));
                if (roleIds.remove(role.getId())) {
                    Integer[] temp = new Integer[roleIds.size()];
                    admin.setRoleIds(roleIds.toArray(temp));
                    AdminExample adminExample1 = new AdminExample();
                    AdminExample.Criteria criteria1 = adminExample1.createCriteria();
                    criteria1.andIdEqualTo(admin.getId());
                    criteria1.andDeletedEqualTo(false);
                    adminMapper.updateByExample(admin, adminExample1);
                }
            }
        }
    }

    @Override
    /**
     * @author: lixiaosheng
     * @description: 获取当前角色的权限和所有资源权限
     * @date: 2022/5/7 22:08
     */
    public PermissionDataVO getPermissions(String roleId) {
        PermissionDataVO permissionDataVO = new PermissionDataVO();
        List<String> assignedPermissions = permissionMapper.selectPermissionByRoleId(roleId);
        permissionDataVO.setAssignedPermissions(assignedPermissions);

        List<SystemPermissionsVO> systemPermissions = resourceTableMapper.select();
        for (SystemPermissionsVO permission : systemPermissions) {
            Integer pid = resourceTableMapper.selectPidByIdAndCidIsNull(permission.getId());
            List<ChildrenVO> children = resourceTableMapper.selectByCid(pid);
            permission.setChildren(children);
        }
        for (SystemPermissionsVO permission : systemPermissions) {
            Integer pid1 = resourceTableMapper.selectPidByIdAndCidIsNull(permission.getId());
            for (ChildrenVO child : permission.getChildren()) {
                Integer pid = resourceTableMapper.selectPidByIdAndCid(child.getId(), pid1);
                List<Integer> cid = resourceTableMapper.selectPidByCid(pid);
                List<CChildrenVO> CChildrenVOS = new ArrayList<>();
                for (Integer integer : cid) {
                    CChildrenVO CChildrenVO = resourceTableMapper.selectApiByRid(integer);
                    CChildrenVOS.add(CChildrenVO);
                }
                child.setChildren(CChildrenVOS);
            }
        }
        permissionDataVO.setSystemPermissions(systemPermissions);

        return permissionDataVO;
    }

    @Override
    /**
     * @author: lixiaosheng
     * @description: 更新角色的权限
     * @date: 2022/5/8 12:59
     */
    public void updatePermissions(RolePermissionBO permissionBO) {

        List<String> newPermissions = permissionBO.getPermissions();
        List<String> oldPermissions = permissionMapper.selectPermissionByRoleId(permissionBO.getRoleId().toString());

        // 物理删除
        // for (String newPermission : newPermissions) {
        //     if (!oldPermissions.contains(newPermission)) {
        //         Permission p1 = new Permission();
        //         p1.setDeleted(false);
        //         p1.setUpdateTime(new Date());
        //         p1.setPermission(newPermission);
        //         p1.setRoleId(permissionBO.getRoleId());
        //         p1.setAddTime(new Date());
        //         permissionMapper.insert(p1);
        //     }
        // }
        // for (String oldPermission : oldPermissions) {
        //     if (!newPermissions.contains(oldPermission)) {
        //         PermissionExample example = new PermissionExample();
        //         PermissionExample.Criteria criteria = example.createCriteria();
        //         criteria.andRoleIdEqualTo(permissionBO.getRoleId());
        //         criteria.andPermissionEqualTo(oldPermission);
        //         permissionMapper.deleteByExample(example);
        //     }
        // }

        // 逻辑删除
        for (String newPermission : newPermissions) {
            if (!oldPermissions.contains(newPermission)) {
                Permission p1 = new Permission();
                p1.setDeleted(false);
                p1.setUpdateTime(new Date());
                p1.setPermission(newPermission);
                p1.setRoleId(permissionBO.getRoleId());
                p1.setAddTime(new Date());
                permissionMapper.insert(p1);
            }
        }
        for (String oldPermission : oldPermissions) {
            if (!newPermissions.contains(oldPermission)) {
                PermissionExample example = new PermissionExample();
                PermissionExample.Criteria criteria = example.createCriteria();
                criteria.andRoleIdEqualTo(permissionBO.getRoleId());
                criteria.andPermissionEqualTo(oldPermission);
                Permission p = new Permission();
                p.setDeleted(true);
                permissionMapper.updateByExampleSelective(p, example);
            }
        }
    }
}
